package com.frank.code_notes.C01_array;

import java.util.Arrays;

/**
 * @Description 977. 有序数组的平方
 * @Author zhoujr
 * @Data 2024/11/23 16:32
 */
public class L977ArraySquared {

    /**
     * @Description 暴力排序
     */
    public static int[] sortedSquares(int[] nums) {
        for (int i = 0; i < nums.length; i++) {
            nums[i] = nums[i] * nums[i];
        }
        Arrays.sort(nums);
        return nums;
        // return Arrays.stream(nums).map(i -> i*i).sorted().toArray();
    }

    /**
     * @Description 双指针，平方最大值是从两端开始的
     */
    public static int[] sortedTwo(int[] nums) {
        int[] res = new int[nums.length];
        int k = nums.length - 1, left = 0, right = nums.length - 1;
        while (left <= right) {
            if (nums[left] * nums[left] > nums[right] * nums[right]) {
                res[k--] = nums[left] * nums[left++];
            } else {
                res[k--] = nums[right] * nums[right--];
            }
        }
        return res;
    }


    public static void main(String[] args) {
        int[] intArray = sortedSquares(new int[]{-7, -3, 2, 3, 11});
        System.out.println(Arrays.toString(intArray));
        int[] intArrayTwo = sortedTwo(new int[]{-7, -3, 2, 3, 11});
        System.out.println(Arrays.toString(intArrayTwo));
    }

}
